﻿using Application.Common.Interfaces;
using Common.Events;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Common.Hubs;
using Microsoft.AspNetCore.SignalR;
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Common.MessageTemplates;
using Common.Enums;
using Common.Utils;
using Domain.Entities.Identity;

namespace Application.Features.Roles.EventHandlers;


public class UpdateMenuEventHandler : INotificationHandler<UpdatedEvent<Menu>>
{
    private readonly ILogger<UpdateMenuEventHandler> _logger;
    private readonly IServiceProvider _serviceProvider;
    private readonly IHubContext<SignalRHub> _hubContext;

    public UpdateMenuEventHandler(
        ILogger<UpdateMenuEventHandler> logger,
        IServiceProvider serviceProvider,
        IHubContext<SignalRHub> hubContext)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
        _hubContext = hubContext;
    }

    public Task Handle(UpdatedEvent<Menu> notification, CancellationToken cancellationToken)
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var _context = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
            if (!_context.Roles.Any()) return Task.CompletedTask;

            var receiveMessageUsers = _context.Users
                .Include(ur => ur.UserRoles)
                    .ThenInclude(r => r.Role)
                        .ThenInclude(rm => rm.RoleMenus)
                .Where(u => u.UserRoles.Any(ur => ur.Role.RoleMenus.Any(rm => rm.MenuId == notification.Entity.Id)))
                .ToList();
            if (!receiveMessageUsers.Any()) return Task.CompletedTask;

            foreach (var user in receiveMessageUsers) 
            {
                Random random = new Random();
                SignalRMessageTemplate signalRMessageTemplate = new SignalRMessageTemplate()
                {
                    Id = random.Next(999999999),
                    MessageType = MessageType.UpdateMenu,
                    Content = $"你所拥有的菜单:【{notification.Entity.Name}】发生了修改",
                    Username = user.UserName!
                };
                _hubContext.Clients.User(user.Id.ToString()).SendAsync("ReceivePrivateMessage", signalRMessageTemplate.ToJson(true, true));
            }
        }
        return Task.CompletedTask;
    }
}